package com.afishing.servlet;

import com.afishing.dao.UserDao;
import com.afishing.dao.impl.UserDaoImpl;
import com.afishing.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "UpdateProfileServlet", value = "/updateProfile")
public class UpdateProfileServlet extends HttpServlet {
    private final UserDao userDao = new UserDaoImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        // 获取表单提交的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 从会话中获取当前用户
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 更新用户信息
        user.setUsername(username);
        user.setPassword(password);

        // 保存更新后的用户信息到数据库
        userDao.updateUser(user);

        // 将更新后的用户信息保存到会话中
        request.getSession().setAttribute("user", user);

        // 重定向到个人中心页面
        response.sendRedirect("profile.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}